#!/bin/sh

OSLAB_PATH=$PWD

install_gcc34() {
    echo -n "* Install gcc-3.4 for x86(i386) arch now......"
    if [ -z `which gcc-3.4` ]; then
        tar xJf gcc-3.4_amd64.tar.xz
        sudo dpkg -i gcc-3.4_amd64/gcc-3.4-base_3.4.6-8ubuntu2_amd64.deb
        sudo dpkg -i gcc-3.4_amd64/cpp-3.4_3.4.6-8ubuntu2_amd64.deb
        sudo dpkg -i gcc-3.4_amd64/gcc-3.4_3.4.6-8ubuntu2_amd64.deb
	rm gcc-3.4_amd64 -rf
        echo "\033[34mDone\033[0m"
    else
        echo "\033[33mSkipped\033[0m"
    fi
}

install_dep_i386() {
    echo "* Install x86(i386) dependencies for x86_64(amd64) arch now......"
    # Install bin86
    echo -n "* Install bin86 that includes as86 and ld86 for compiling and linking bootsect.s and setup.s"
    sudo apt-get install bin86 -y
    echo "\033[34mDone\033[0m"

    # Install 32bit libs
    echo -n "* Install 32bit libs"
    sudo apt-get install libc6-dev-i386 -y
    echo "\033[34mDone\033[0m"

    # Install compilation environment for C
    echo -n "* Install compilation environment for C"
    sudo apt-get install build-essential -y
    echo "\033[34mDone\033[0m"

    # Install libSM:i386 for bochs
    echo -n "* Install libSM:i386 for bochs"
    sudo apt-get install libsm6:i386 -y
    echo "\033[34mDone\033[0m"

    # Install libX11-6:i386 for bochs
    echo -n "* Install libX11-6:i386 for bochs"
    sudo apt-get install libx11-6:i386 -y
    echo "\033[34mDone\033[0m"

    # Install libxpm4:i386 for bochs
    echo -n "* Install libxpm4:i386 for bochs"
    sudo apt-get install libxpm4:i386 -y
    echo "\033[34mDone\033[0m"
    echo "* Install x86(i386) dependencies for x86_64(amd64) arch finished \033[34mDone\033[0m"
}

cd $OSLAB_PATH/start

# Common Code
if [ "$1" ] && [ "$1" = "-s" ];
then
    echo "\r* Update apt sources......                                 "
    sudo apt-get update
    install_dep_i386
    install_gcc34
else
    echo -n "* Begin to setup......\033[33m3\033[0m sec to start"; sleep 1
    echo -n "\r* Begin to setup......\033[33m2\033[0m sec to start"; sleep 1
    echo -n "\r* Begin to setup......\033[33m1\033[0m sec to start"; sleep 1
    echo "\r* Begin to setup......                                 \033[0m"
fi

# Extract linux-0.11 and bochs and hdc image
echo -n "* Extract linux-0.11 and bochs and hdc image......"
tar xJf oslab.tar.xz -C $OSLAB_PATH
cp $OSLAB_PATH/start/.vscode/ $OSLAB_PATH/oslab -rf
cd $OSLAB_PATH/oslab
./run init
cd linux-0.11
make
cd ..
./run
echo "\033[34mDone\033[0m"

echo "\033[34m* Installation finished.\033[0m"
